//APP更新
import whApp from '@/api/login.js'

const timeoutDefault = 259200

function getToken() {
	let _whapp = new whApp()
	_whapp.refreshToken({
		jwt_token: uni.getStorageSync("newToken")
	}).then(res => {
		if(res.code == 200){
			const localData = {
				timeout: timeoutDefault,
				createTime: Date.now()
			}
			try {
				uni.setStorageSync( 'newToken_Obj', localData)
				uni.setStorageSync('newToken', res.data.token)
				// #ifdef H5
				this.$cookies.set("DedeUserID", res.data.cookie.DedeUserID);
				this.$cookies.set("DedeLoginTime__ckMd5", res.data.cookie.DedeLoginTime__ckMd5);
				this.$cookies.set("DedeLoginTime", res.data.cookie.DedeLoginTime);
				this.$cookies.set("DedeUserID__ckMd5", res.data.cookie.DedeUserID__ckMd5);
				// #endif
				// 给主包传token
				uni.sendHostEvent('token', {
					'tokenObj': JSON.stringify(localData),
					'token':  res.data.token
				}, (ret) => {
					//发送消息成功回调
					console.log('Send event to Host: ' + JSON.stringify(ret));
				});
			} catch (e) {}
		}
	})
}


function isTokenTimeout(name) {
	let token = uni.getStorageSync(name)
	let data = uni.getStorageSync(name + "_Obj" )
	if (!data) return true
	if (data.timeout === 0) return false
	const currentTime = Date.now()
	const overTime = (currentTime - data.createTime) / 1000
	if (overTime > data.timeout) {
		getToken()
		return true
	}
	return false
}

export default function renewToken(option) {
	// console.log(option, '######################')
	let isrenewToken = false
	if(option.referrerInfo){
		let extraData = option.referrerInfo.extraData;
		if(extraData && extraData.token){
			let objData = JSON.parse(extraData.tokenObj)
			let token = extraData.token || ''
			uni.setStorageSync('newToken_Obj',  objData)
			uni.setStorageSync('newToken', token)
			let timeOut = isTokenTimeout('newToken')
			isrenewToken = true
		}
	}
	if(option.query && option.query.newCode){
		uni.setStorageSync('newCode', option.query.newCode)
	}
	// 获取通过webview跳转的token
	if(option.query && option.query.jwt_token){
		uni.setStorageSync('newToken', option.query.jwt_token)
	}
	// 获取通过webview跳转的token
	if(option.query && option.query.tokenObj){
		// console.log(JSON.stringify(option.query.jwt_token), 'token##############')
		let tokenObj = JSON.parse(option.query.tokenObj)
		uni.setStorageSync('newToken_Obj',  tokenObj)
	}
	if(!isrenewToken){
		let tokenObj = uni.getStorageSync( 'newToken_Obj');
		if(tokenObj){
			let timeOut = isTokenTimeout('newToken')
		}else{
			getToken()
		}
	}
}
